<template>
  <view class="search-page">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="header-content">
        <view class="back-icon" @click="goBack">
          <uni-icons type="left" size="20" color="#333"></uni-icons>
        </view>
        <view class="search-input-wrapper">
          <view class="search-box">
            <uni-icons type="search" size="18" color="#999"></uni-icons>
            <input 
              type="text" 
              v-model="keyword" 
              focus
              confirm-type="search"
              @confirm="doSearch(false)"
              :placeholder="defaultKeyword"
              class="search-input"
              placeholder-class="placeholder"
            />
          </view>
        </view>
        <view class="search-btn" @tap="doSearch(false)">搜索</view>
      </view>
  </view>

    <!-- 搜索内容 -->
    <view class="search-content">
      <!-- 搜索建议列表 -->
      <scroll-view class="keyword-list-box" v-show="isShowKeywordList" scroll-y>
        <view v-for="(row,index) in keywordList" :key="index"
              class="keyword-entry" hover-class="keyword-entry-tap"
              @tap.stop="doSearch(keywordList[index].keyword)">
          <view class="keyword-text">
              <rich-text :nodes="row.htmlStr"></rich-text>
            </view>
          <view class="keyword-img" @tap.stop="setKeyword(row.keyword)">
            <uni-icons type="arrow-left" size="16" color="#999"></uni-icons>
          </view>
        </view>
        <view class="empty-result" v-if="keywordList.length === 0">
          <text>暂无搜索结果</text>
        </view>
      </scroll-view>
      
      <!-- 历史记录和热门品牌 -->
      <view class="search-default" v-show="!isShowKeywordList">
        <!-- 热门品牌 -->
        <view class="section">
          <view class="section-header">
            <view class="section-title">
              <view class="title-line"></view>
              <text>热门品牌</text>
            </view>
            <view class="section-action" @tap="hotToggle">
              <uni-icons :type="forbid ? 'eye-slash' : 'eye'" size="18" color="#999"></uni-icons>
            </view>
          </view>
          
          <view class="tag-wrapper" v-if="forbid==''">
            <view 
              class="tag-item" 
              v-for="(keyword,index) in hotKeywordList" 
              :key="index"
              @tap="doSearch(keyword)"
            >{{ keyword }}</view>
          </view>
          <view class="empty-data" v-else>
            <text>热门品牌已隐藏</text>
          </view>
        </view>
        
        <!-- 历史搜索 -->
        <view class="section" v-if="oldKeywordList.length>0">
          <view class="section-header">
            <view class="section-title">
              <view class="title-line"></view>
              <text>历史搜索</text>
            </view>
            <view class="section-action" @tap="oldDelete">
              <uni-icons type="trash" size="18" color="#999"></uni-icons>
            </view>
          </view>
          
          <view class="tag-wrapper">
            <view 
              class="tag-item" 
              v-for="(keyword,index) in oldKeywordList" 
              :key="index"
              @tap="doSearch(keyword)"
            >{{ keyword }}</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import Navbar from '@/components/navbar/index.vue'
import {listProductBrandNoPage} from "@/api/sell/productBrand";
import UniIcons from "@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue";

export default {
  data() {
    return {
      defaultKeyword: "",
      keyword: "",
      oldKeywordList: [],
      hotKeywordList: [],
      keywordList: [],
      forbid: '',
      isShowKeywordList: false,
      statusBarHeight: 20 // 默认状态栏高度
    }
  },
  onLoad() {
    this.init();
    this.getStatusBarHeight();
  },
  components: {
    UniIcons,
    Navbar,
  },
  watch: {
    keyword(val) {
      this.inputChange(val);
    }
  },
  methods: {
    // 获取状态栏高度
    getStatusBarHeight() {
      uni.getSystemInfo({
        success: (res) => {
          this.statusBarHeight = res.statusBarHeight;
        }
      });
    },
    goBack() {
      uni.navigateBack();
    },
    init() {
      this.loadDefaultKeyword();
      this.loadOldKeyword();
      this.loadHotKeyword();
    },
    //加载默认搜索关键字
    loadDefaultKeyword() {
      this.defaultKeyword = "请搜索";
    },
    //加载历史搜索,自动读取本地Storage
    loadOldKeyword() {
      uni.getStorage({
        key: 'OldKeys',
        success: (res) => {
          var OldKeys = JSON.parse(res.data);
          this.oldKeywordList = OldKeys;
        }
      });
    },
    //加载热门品牌
    async loadHotKeyword() {
      const {data} = await listProductBrandNoPage();
      this.hotKeywordList = data.map(item => item.brandName);
    },
    //监听输入
    inputChange(event) {
      //兼容引入组件时传入参数情况
      var keyword = event.detail ? event.detail.value : event;
      if (!keyword) {
        this.keywordList = [];
        this.isShowKeywordList = false;
        return;
      }
      this.isShowKeywordList = true;
      //以下示例截取淘宝的关键字，请替换成你的接口
      uni.request({
        url: 'https://suggest.taobao.com/sug?code=utf-8&q=' + keyword, //仅为示例
        success: (res) => {
          this.keywordList = [];
          this.keywordList = this.drawCorrelativeKeyword(res.data.result, keyword);
        }
      });
    },
    //高亮关键字
    drawCorrelativeKeyword(keywords, keyword) {
      var len = keywords.length,
          keywordArr = [];
      for (var i = 0; i < len; i++) {
        var row = keywords[i];
        var html = row[0].replace(keyword, "<span style='color: #e84d1c;'>" + keyword + "</span>");
        html = '<div>' + html + '</div>';
        var tmpObj = {
          keyword: row[0],
          htmlStr: html
        };
        keywordArr.push(tmpObj)
      }
      return keywordArr;
    },
    //顶置关键字
    setKeyword(keyword) {
      this.keyword = keyword;
    },
    //清除历史搜索
    oldDelete() {
      this.$confirmDialog.confirm('确定清除历史搜索记录？').then(() => {
        this.oldKeywordList = [];
        uni.removeStorage({
          key: 'OldKeys'
        });
      });
    },
    //热门品牌开关
    hotToggle() {
      this.forbid = this.forbid ? '' : '_forbid';
    },
    //执行搜索
    doSearch(keyword) {
      keyword = keyword === false ? this.keyword : keyword;
      this.keyword = keyword;
      if (this.keyword.trim() === '') {
        uni.showToast({
          title: '请输入搜索关键字',
          icon: 'none',
          duration: 2000
        })
        return;
      }
      this.saveKeyword(keyword); //保存为历史
      uni.navigateTo({
        url: '/pages/sellment/product/list?keyword=' + keyword
      })
    },
    //保存关键字到历史记录
    saveKeyword(keyword) {
      uni.getStorage({
        key: 'OldKeys',
        success: (res) => {
          var OldKeys = JSON.parse(res.data);
          var findIndex = OldKeys.indexOf(keyword);
          if (findIndex == -1) {
            OldKeys.unshift(keyword);
          } else {
            OldKeys.splice(findIndex, 1);
            OldKeys.unshift(keyword);
          }
          //最多10个纪录
          OldKeys.length > 10 && OldKeys.pop();
          uni.setStorage({
            key: 'OldKeys',
            data: JSON.stringify(OldKeys)
          });
          this.oldKeywordList = OldKeys; //更新历史搜索
        },
        fail: (e) => {
          var OldKeys = [keyword];
          uni.setStorage({
            key: 'OldKeys',
            data: JSON.stringify(OldKeys)
          });
          this.oldKeywordList = OldKeys; //更新历史搜索
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.search-page {
  background-color: #f8f8f8;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.status-bar {
  background-color: #f8f8f8;
  width: 100%;
}

/* 搜索头部 */
.search-header {
  background-color: #f8f8f8;
  padding: 10rpx 0;
  border-bottom: 1rpx solid #eee;
  position: sticky;
  top: 0;
  z-index: 9;
  width: 100%;
  
  .header-content {
    display: flex;
    align-items: center;
    padding: 0 30rpx;
  }
  
  .back-icon {
    width: 50rpx;
    height: 50rpx;
  display: flex;
  align-items: center;
    justify-content: flex-start;
}

  .search-input-wrapper {
    flex: 1;
    margin: 0 20rpx;
  }
  
  .search-box {
  display: flex;
  align-items: center;
    background-color: #fff;
    border-radius: 36rpx;
    padding: 0 24rpx;
    height: 64rpx;
}

  .search-input {
    flex: 1;
    height: 64rpx;
    font-size: 28rpx;
    margin-left: 12rpx;
  }
  
  .placeholder {
    color: #999;
    font-size: 28rpx;
  }
  
  .search-btn {
    background-color: #e84d1c;
    color: #fff;
    padding: 0 30rpx;
    height: 64rpx;
    line-height: 64rpx;
    border-radius: 32rpx;
    font-size: 28rpx;
    
    &:active {
      opacity: 0.9;
}
  }
}

/* 搜索内容 */
.search-content {
  padding: 30rpx;
  flex: 1;
  overflow-y: auto;
}

/* 搜索建议列表 */
.keyword-list-box {
  max-height: calc(100vh - 150rpx);
}

.keyword-entry {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f2f2f2;
}

.keyword-entry-tap {
  background-color: #f9f9f9;
}

.keyword-text {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.keyword-img {
  width: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-result {
  padding: 100rpx 0;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}

/* 默认搜索内容 */
.search-default {
  
}

.section {
  margin-bottom: 50rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.title-line {
  width: 6rpx;
  height: 30rpx;
  background-color: #e84d1c;
  margin-right: 16rpx;
  border-radius: 3rpx;
}

.section-action {
  padding: 10rpx;
}

.tag-wrapper {
  display: flex;
  flex-wrap: wrap;
}

.tag-item {
  background-color: #fff;
  border-radius: 32rpx;
  padding: 14rpx 30rpx;
  margin: 0 20rpx 20rpx 0;
  font-size: 26rpx;
  color: #666;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  
  &:active {
    background-color: #fff0e8;
    color: #e84d1c;
  }
}

.empty-data {
  padding: 40rpx 0;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}
</style>
